package com.yzz.hzraisedust.hzraseidust.Login;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.PopupWindow.OnDismissListener;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.yzz.hzraisedust.hzraseidust.R;
import com.yzz.hzraisedust.hzraseidust.main.InfoActivity;
import com.yzz.hzraisedust.hzraseidust.modelbean.LoginInfo;
import com.yzz.hzraisedust.hzraseidust.util.Constant;
import com.yzz.hzraisedust.hzraseidust.util.NetUtil;


public class LoginActivity extends Activity implements OnClickListener,
        OnItemClickListener, OnDismissListener,Response.Listener<String>,Response.ErrorListener {
    protected static final String TAG = "LoginActivity";
    private LinearLayout mLoginLinearLayout; //登录框
    private LinearLayout mUserIdLinearLayout; // 用户名
    private Animation mTranslate; // 动画效果
    private Dialog mLoginingDlg; // 登录框
    private EditText mIdEditText; // 用户名输入框
    private EditText mPwdEditText; // 密码输入框
    private ImageView mMoreUser; // 更多用户
    private Button mLoginButton; // 登录按钮
    private ImageView mLoginMoreUserView; // 更多用户
    private String mIdString;
    private String mPwdString;
    private ArrayList<User> mUsers; // 用户列表
    private ListView mUserIdListView; // 用户列表界面
    private MyAapter mAdapter; // 用户列表的Adapter
    private PopupWindow mPop;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        initView();
        setListener();
        mLoginLinearLayout.startAnimation(mTranslate); // Y???????

        //获取已经输入的用户列表
        mUsers = Utils.getUserList(LoginActivity.this);
        int size = mUsers.size();
        if (size > 0) {
            //取出最近的一次输入的用户名密码
            mIdEditText.setText(mUsers.get(size-1).getId());
            mPwdEditText.setText(mUsers.get(size-1).getPwd());
        }


        LinearLayout parent = (LinearLayout) getLayoutInflater().inflate(
                R.layout.userifo_listview, null);
        mUserIdListView = (ListView) parent.findViewById(android.R.id.list);
        parent.removeView(mUserIdListView); //不显示用户提示列表
        mUserIdListView.setOnItemClickListener(this); // 点选用户
        mAdapter = new MyAapter(mUsers);
        mUserIdListView.setAdapter(mAdapter);
        //自动登录
        /*
        if(mIdString!=null && mIdString!="" && mPwdString!=null&& mPwdString!=""){
            showLoginingDlg();
            loginSystem();
        }
        */
    }

    @Override
    public void onErrorResponse(VolleyError volleyError) {
        closeLoginingDlg();
        String message = "";
        if(volleyError!=null) {
            message =":"+ volleyError.getLocalizedMessage();
        }
        Toast.makeText(LoginActivity.this, "发生错误"+message,Toast.LENGTH_LONG).show();

    }

    /* ListView的数据源适配器*/
    class MyAapter extends ArrayAdapter<User> {

        public MyAapter(ArrayList<User> users) {
            super(LoginActivity.this, 0, users);
        }

        public View getView(final int position, View convertView,
                            ViewGroup parent) {
            if (convertView == null) {
                convertView = getLayoutInflater().inflate(
                        R.layout.listview_item, null);
            }

            TextView userIdText = (TextView) convertView
                    .findViewById(R.id.listview_userid);
            userIdText.setText(getItem(position).getId());

            ImageView deleteUser = (ImageView) convertView
                    .findViewById(R.id.login_delete_user);
            deleteUser.setOnClickListener(new OnClickListener() {
                //清除用户信息
                @Override
                public void onClick(View v) {

                    if (getItem(position).getId().equals(mIdString)) {
                        //设置输入框为空
                        mIdString = "";
                        mPwdString = "";
                        mIdEditText.setText(mIdString);
                        mPwdEditText.setText(mPwdString);
                    }
                    mUsers.remove(getItem(position));
                    mAdapter.notifyDataSetChanged(); // 更新列表
                }
            });
            return convertView;
        }

    }

    private void setListener() {
        mIdEditText.addTextChangedListener(new TextWatcher() {

            public void onTextChanged(CharSequence s, int start, int before,
                                      int count) {
                mIdString = s.toString();
            }

            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {
            }

            public void afterTextChanged(Editable s) {
            }
        });
        mPwdEditText.addTextChangedListener(new TextWatcher() {

            public void onTextChanged(CharSequence s, int start, int before,
                                      int count) {
                mPwdString = s.toString();
            }

            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {
            }

            public void afterTextChanged(Editable s) {
            }
        });
        mLoginButton.setOnClickListener(this);
        mLoginMoreUserView.setOnClickListener(this);
    }

    private void initView() {
        mIdEditText = (EditText) findViewById(R.id.login_edtId);
        mPwdEditText = (EditText) findViewById(R.id.login_edtPwd);
        mMoreUser = (ImageView) findViewById(R.id.login_more_user);
        mLoginButton = (Button) findViewById(R.id.login_btnLogin);
        mLoginMoreUserView = (ImageView) findViewById(R.id.login_more_user);
        mLoginLinearLayout = (LinearLayout) findViewById(R.id.login_linearLayout);
        mUserIdLinearLayout = (LinearLayout) findViewById(R.id.userId_LinearLayout);
        mTranslate = AnimationUtils.loadAnimation(this, R.anim.my_translate); // ?????????????
        initLoginingDlg();
    }

    public void initPop() {
        int width = mUserIdLinearLayout.getWidth() - 4;
        int height = LayoutParams.WRAP_CONTENT;
        mPop = new PopupWindow(mUserIdListView, width, height, true);
        mPop.setOnDismissListener(this);// pop消失的监听事件

        // 设置弹出框背景
        mPop.setBackgroundDrawable(new ColorDrawable(0xffffffff));

    }

    //初始化登录框
    private void initLoginingDlg() {

        mLoginingDlg = new Dialog(this, R.style.loginingDlg);
        mLoginingDlg.setContentView(R.layout.logining_dlg);

        Window window = mLoginingDlg.getWindow();
        WindowManager.LayoutParams params = window.getAttributes();
        // 获取设备分辨率
        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        int cxScreen = dm.widthPixels;
        int cyScreen = dm.heightPixels;

        int height = (int) getResources().getDimension(
                R.dimen.loginingdlg_height);// ??42dp
        int lrMargin = (int) getResources().getDimension(
                R.dimen.loginingdlg_lr_margin); // ???????10dp
        int topMargin = (int) getResources().getDimension(
                R.dimen.loginingdlg_top_margin); // ????20dp

        params.y = (-(cyScreen - height) / 2) + topMargin; // -199


        params.width = cxScreen;
        params.height = height;


        mLoginingDlg.setCanceledOnTouchOutside(true);
    }


    private void showLoginingDlg() {
        if (mLoginingDlg != null)
            mLoginingDlg.show();
    }


    private void closeLoginingDlg() {
        if (mLoginingDlg != null && mLoginingDlg.isShowing())
            mLoginingDlg.dismiss();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.login_btnLogin:
                Log.i(TAG, mIdString + "  " + mPwdString);
                if (mIdString == null || mIdString.equals("")) {
                    Toast.makeText(LoginActivity.this, "用户名不能为空", Toast.LENGTH_SHORT)
                            .show();
                } else if (mPwdString == null || mPwdString.equals("")) {
                    Toast.makeText(LoginActivity.this, "密码不能为空", Toast.LENGTH_SHORT)
                            .show();
                } else {
                    //开始登录
                    showLoginingDlg();
                    loginSystem();
                    boolean mIsSave = true;
                    try {
                        for (User user : mUsers) {
                            user.setSelect(false);
                            if (user.getId().equals(mIdString)) {
                               if(user.getPwd().equals(mPwdString)) {
                                   mIsSave = false;
                               }else{
                                   mUsers.remove(user);
                               }
                                break;
                            }
                        }
                        if (mIsSave) {
                            User user = new User(mIdString, mPwdString);
                            user.setSelect(true);
                            mUsers.add(user);
                        }

                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                }
                break;
            case R.id.login_more_user:
                if (mPop == null) {
                    initPop();
                }
                if (!mPop.isShowing() && mUsers.size() > 0) {
                    mMoreUser.setImageResource(R.mipmap.login_more_down); // ?��????
                    mPop.showAsDropDown(mUserIdLinearLayout, 2, 1); // ???????????
                }
                break;
            default:
                break;
        }

    }

    private void loginSystem(){
        NetUtil netUtil  = new NetUtil(LoginActivity.this.getApplicationContext());
        //登录参数
        Map<String,String> map = new HashMap<String, String>();
        map.put("userName",mIdString);
        map.put("passWord",mPwdString);
        netUtil.requestData(this, this,Constant.LOGIN_URL,map);
    }
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position,
                            long id) {
        mIdEditText.setText(mUsers.get(position).getId());
        mPwdEditText.setText(mUsers.get(position).getPwd());
        mPop.dismiss();
    }


    @Override
    public void onDismiss() {

        mMoreUser.setImageResource(R.mipmap.login_more_up);
    }


    @Override
    public void onPause() {
        super.onPause();
        try {
            Utils.saveUserList(LoginActivity.this, mUsers);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    @Override
    public void onResponse(String result){
        Gson gson = new Gson();
        LoginInfo loginInfo = gson.fromJson(result,LoginInfo.class);
        if(loginInfo!=null){
            //登录成功
            if(loginInfo.isSuccess()){
                SharedPreferences sharedPreferences = getSharedPreferences(Constant.USERINFO, Context.MODE_PRIVATE);
                SharedPreferences.Editor editor=sharedPreferences.edit();
                editor.putString(Constant.UID_KEY, loginInfo.getUid());
                editor.commit();
                Constant.Uid = loginInfo.getUid();
                Intent intent = new Intent(LoginActivity.this, InfoActivity.class);
                startActivity(intent);
                finish();
            }else{//登录失败

            }
            Toast.makeText(LoginActivity.this, loginInfo.getMessage(), Toast.LENGTH_SHORT).show();

        }else {//登录失败
            Toast.makeText(LoginActivity.this, "", Toast.LENGTH_SHORT).show();
        }
        closeLoginingDlg();//
    }

}
